import React, {Component} from 'react'
import PropTypes from 'react-router/lib/PropTypes'

import {Tabs, Modal, Button, message} from 'antd'
const TabPane = Tabs.TabPane
const Confirm = Modal.confirm

import { WeaRichText, WeaDialog, WeaNewScroll } from 'ecCom'

//import WeaCkEditor from "../../Component/wea-ckeditor/CKEAppend"
import WeaWhitePage from "../../Component/wea-white-page"

import WeiboBar from "../RightContainer/Weibo/WeiboBar"

import ComVar from "../RightContainer/ComVar"
const {PublicRangeType, ComeFrom} = ComVar

import {WeaTools, WeaTop, WeaLeftRightLayout} from 'ecCom'
import Utils from './Utils'
const {RangeStar, BasicInfoCard, ToolTipBar, CustomerList, MessageItem} = Utils

import WeaCircleImage from "../../Component/wea-circle-image"

import WeaUtils from "../../Component/wea-utils"
const {DateFormat} = WeaUtils

import Mood from "../RightContainer/Weibo/Mood"
import _trim from 'lodash/trim';

import * as Util from '../../../util/index'
import Dict from '../../Component/wea-blog-dict';

const mirror = Dict.bottomBarMirror;


class LeftContiner extends Component {
    static contextTypes = {
        router: PropTypes.routerShape
    }

    constructor(props) {
        super(props)
        this.state = {
            showWorkRecord: false,
            showOperation: false,

            modalMessageVisible: false,
            modalTagVisible: false,

            authType: PublicRangeType.public,
            authRange: [],
            
            mood: '1',
        }
        this.CKE_ID = "wea_ckeditor_weibo_tag"
        this.onTempletChange = this.onTempletChange.bind(this);
    }

    componentDidMount() {
        const {actions} = this.props
        actions.getIndexInfo()
        actions.getBasicInfo()
        actions.getReceiverList({
            recordType: "visit",
            currentPage: 1,
            pageSize: 5
        })
        actions.getVisitorList({
            recordType: "access",
            currentPage: 1,
            pageSize: 5
        })
    }

    render() {
        let {authType, authRange} = this.state,
            {cardType, onClick, indexInfo = {}, basicInfo: {countData = {}}, userInfo = {}, receiverList, visitorList, messageList, note, actions, weiboCKEditorConfig} = this.props,
            {currentUser = {}} = userInfo,
            basicInfoCard = [
                {
                    id: 1,
                    name: '微博主页',
                    value: countData.updateCount,
                    color: '#447eff',
                    onClick: () => {
                        onClick(1)
                    },
                    isActive: cardType == 1,
                    border: ["top", "right", "bottom"]
                },
                {
                    id: 2,
                    name: '我的微博',
                    value: countData.blogCount,
                    color: '#ff7725',
                    onClick: () => {
                        onClick(2)
                    },
                    isActive: cardType == 2,
                    border: ["top", "bottom"]
                },
                {
                    id: 3,
                    name: '我的粉丝',
                    value: countData.attentionMeTotalCount,
                    color: '#cc31ff',
                    onClick: () => {
                        onClick(3)
                    },
                    isActive: cardType == 3,
                    border: ["bottom", "right"]
                },
                {
                    id: 4,
                    name: '我的关注',
                    value: countData.myAttentionCount,
                    color: '#53c97a',
                    onClick: () => {
                        onClick(4)
                    },
                    isActive: cardType == 4,
                    border: ["bottom"]
                }
            ],
            toolTipBar = [
                {
                    name: '消息提醒',
                    color: '#32a8ff',
                    icon: 'icon-blog-MessageReminder',
                    tips: countData.remindCount,
                    onClick: () => this.setModalMessageVisible(true)
                },
                {
                    name: '微博便签',
                    color: '#f5b400',
                    icon: 'icon-blog-Note',
                    tips: "",
                    onClick: () => this.setModalTagVisible(true)
                }
            ],
            messages = (messageList.remindList || []).map(
                item => {
                    const {id, username, msg, remindType, relatedid} = item,
                        params = {
                            id: id,
                            name: username,
                            type: remindType,
                            tips: msg,
                            relatedId: relatedid,
                            url: '',
                            onIgnoreClick: this.setMessageIgnore
                        }
                    if (remindType == 1) params.onAttentionClick = this.setAttentionStatus
                    return params
                }
            ),
            rangeStar = []

        if(indexInfo.work)
            rangeStar.push({
                name: '工作指数',
                tip: indexInfo.work ? indexInfo.work.workIndexTitle : null,
                value: indexInfo.work ? indexInfo.work.workIndex : 0.0
            })
        if(indexInfo.mood)
            rangeStar.push({
                name: '心情指数',
                tip: indexInfo.mood ? indexInfo.mood.moodIndexTitle : null,
                value: indexInfo.mood ? indexInfo.mood.moodIndex : 0.0
            })
        if(indexInfo.schedule)
            rangeStar.push({
                name: '考勤指数',
                tip: indexInfo.schedule ? indexInfo.schedule.scheduleTitle : null,
                value: indexInfo.schedule ? indexInfo.schedule.scheduleIndex : 0.0
            })
        
        //暂时接入过来 zxt
        let bottomBarConfig = [];
        
        weiboCKEditorConfig && weiboCKEditorConfig.appList && weiboCKEditorConfig.appList.map(cg => {
        	cg.name === 'selects' && bottomBarConfig.push({
        		name: 'Component', 
        		show: <Mood onSelect={mood => this.setState({mood})}/>
        	})
        	cg.name === 'dialogs' && cg.items.map(item => {
	        	let obj = { 
	        		isBlog: true,
	        		name: 'Browser', 
	        		show: <div className="wea-cb-item">
	                    <span className={`wea-cbi-icon ${mirror[item].icon}`}/>
	                    <span className="wea-cbi-text">{mirror[item].name}</span>
	                </div>,
	        		type: mirror[item].type, 
	        		title: mirror[item].name,
	        		isSingle: item === 'Templet',
	        	};
	        	if(item === 'Templet') obj.onToolsChange = this.onTempletChange
	        	bottomBarConfig.push(obj);
	        })
        	cg.name === 'uploads' && cg.items.map(item => {
	        	bottomBarConfig.push({ 
	        		isBlog: true,
	        		name: 'Upload', 
	        		show: <div className="wea-cb-item">
	        	        <span className='wea-cbi-icon icon-blog-Enclosure'/>
	        	        <span className="wea-cbi-text">附件</span>
	        	    </div>,
	        		uploadId: 'webo_edit', 
	        		uploadUrl: `${item.Attachment.uploadUrl}?category=${item.Attachment.position}`, 
	        		category: item.Attachment.position, 
	        		maxUploadSize: item.Attachment.maxSize,
	        		style: {display: "inline-block", padding: 0}
	        	})
	        })
        })
        //暂时接入过来 zxt

        return (
            <div className="wea-left-container">
                <div className="wea-lc-item wea-lc-top">
                    <div className="wea-lct-image">
                        <WeaCircleImage diameter={70} src={currentUser.imageUrl || ""}
                                        name={currentUser.lastname || ""}/>
                    </div>
                    <div className="wea-lct-desc">
                        {
                            rangeStar.map(item => {
                                return <RangeStar {...item}/>
                            })
                        }
                    </div>
                </div>
                <div className="wea-lc-item wea-lc-middle">
                    {
                        basicInfoCard.map((item, key) => {
                            return <BasicInfoCard {...item} className={key % 2 == 0 ? 'wea-lcc-even' : 'wea-lcc-odd'}/>
                        })
                    }
                </div>
                <div className="wea-lc-item wea-lc-bottom">
                    {
                        toolTipBar.map(item => {
                            return <ToolTipBar {...item}/>
                        })
                    }
                </div>
                <Tabs defaultActiveKey="1" size="small" className={'wea-basic-customer'} animated={false}>
                    <TabPane tab="最近来访" key="1">
                        <CustomerList type="visit" records={receiverList} getList={actions.getReceiverList}/>
                    </TabPane>
                    <TabPane tab="最近访问" key="2">
                        <CustomerList type="access" records={visitorList} getList={actions.getVisitorList}/>
                    </TabPane>
                </Tabs>
                <WeaDialog
                    title="消息提醒"
                    icon="icon-coms-blog"
                    iconBgcolor="#6d3cf7"
                    buttons={[
                        <Button
                            key="ignore" type="primary"
                            disabled={!!!messages.length}
                            onClick={() => this.setMessageIgnore()}
                        >全部忽略</Button>,
                        <Button
                            key="back" type="ghost"
                            onClick={() => this.setModalMessageVisible(false)}
                        >取消</Button>
                    ]}
                    style={{width: 720, height: 520}}
                    visible={this.state.modalMessageVisible}
                    onCancel={() => this.setModalMessageVisible(false)}
                >
                    <WeaNewScroll height="520">
                        {
                            messages && messages.length > 0 ? (
                                messages.map(item => {
                                    return <MessageItem {...item}/>
                                })
                            ) : <WeaWhitePage height="520" type="message"/>
                        }
                    </WeaNewScroll>
                </WeaDialog>
                <WeaDialog
                    title="微博便签"
                    icon="icon-coms-blog"
                    iconBgcolor="#6d3cf7"
                    buttons={[
                        <WeiboBar
                            authType={authType}
                            authRange={authRange}
                            onAuthType={this.onAuthType}
                            onAuthRange={this.onAuthRange}
                            cancelClick={this.cancelTag}
                            publishClick={this.publishTag}
                            saveClick={this.saveTag}
                            style={{
                                border: "none",
                                padding: 0,
                                height: 28,
                                lineHeight: 28
                            }}
                        />
                    ]}
                    style={{width:720, height: 520}}
                    visible={this.state.modalTagVisible}
                    onCancel={this.cancelTag}
                >
                    <div className='wea-ckeditor-import-ecCom wea-blog-bianqian'>
                        <WeaRichText 
		            		id={this.CKE_ID}
		                    ref={this.CKE_ID}
		                    value={note.content || ""}
		                    ckConfig={{
		                    	toolbar:[
						            { name: 'document', items: [ 'Source'] },
						            { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
						            { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
						            { name: 'colors', items: [ 'TextColor' ] },
						            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
						            { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] }
						        ],
						        extraPlugins: 'markdown',
		                        height:369,
		                        uploadUrl: '/api/blog/fileupload/uploadimage',
                                resize_enabled: false,
		                    }}
		                    extentsConfig
		                    bottomBarConfig={ bottomBarConfig }
		                    bootomBarStyle={{}}
		                    onChange={v=>{}}
		                    onStatusChange={s => {}}
		                    onToolsChange={Util.transfStr}
		            	/>
                    </div>
                </WeaDialog>
            </div>
        )
    }
    onTempletChange(name, ids, list, type){
    	Util.templetChange(this.refs[this.CKE_ID].getData(),v =>this.refs[this.CKE_ID].setData(v), name, ids, list, type)
    }

    setModalMessageVisible = (modalMessageVisible) => {
        this.setState({modalMessageVisible: modalMessageVisible})
    }

    setMessageIgnore = (id, type) => {
        const {actions} = this.props
        if (id) {
            actions.ignoreMessage(
                {id: id, remindType: type},
                () => {
                    actions.getBasicInfo()
                }
            )
        } else {
            actions.ignoreMessages(
                () => {
                    actions.getBasicInfo()
                }
            )
        }
    }
    setAttentionStatus = (id, relatedId, status) => {
        const {actions} = this.props
        actions.approveMessage(
            {id: id, relatedId: relatedId, opt: status},
            () => {
                actions.getBasicInfo()
            }
        )
    }

    setModalTagVisible = (modalTagVisible) => {
        this.setState({modalTagVisible: modalTagVisible})
    }

    saveTag = () => {
        let contents = this.refs[this.CKE_ID].getData(),
            {actions} = this.props,
            {authType, authRange} = this.state
        let ckref = this.refs[this.CKE_ID];
        if (!ckref.checkMode()) {
            message.error("不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式");
            return;
        }
        actions.saveNote(
            {content: contents},
            result => {
                if (result.status == "1") {
                    actions.getNote()
                }
            }
        )

        this.setModalTagVisible(false)
    }

    publishTag = () => {
        let {actions, cardType} = this.props,
            {authType, authRange, mood} = this.state,
            workdate = DateFormat(new Date(), "yyyy-MM-dd");
        let ckref = this.refs[this.CKE_ID];
        if (!ckref.checkMode()) {
            message.error("不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式");
            return;
        }
        let content = _trim(this.refs[this.CKE_ID].getData()) || '';
        if (!content) {
            message.error("请输入内容");
            return;
        }
        let params = {
            appItemId: mood || "1",
            comefrom: ComeFrom.pc,
            content: content,
            workdate: workdate
        }
    
        actions.editWeibo(params, {workdate: workdate},
            result => {
                if (result.status == "1") {
                    actions.getBasicInfo()
                }
            }
        )

        this.setModalTagVisible(false)
    }

    cancelTag = () => {
        let content = this.props.note.content;
        this.refs[this.CKE_ID].setData(content);
        this.setModalTagVisible(false)
    }
    onAuthType = (authType) => {
        this.setState({authType: authType})
    }

    onAuthRange = (authRange) => {
        this.setState({authRange: authRange})
    }
}

export default LeftContiner